<?php

defined('_JEXEC') or die('Restricted access');

class ConsoleController extends JControllerLegacy {
    protected $baseUrl = "http://getbruce.wiki:8080/intf/e/1/";
    #protected $baseUrl = "http://www.adgyde.com/intf/e/1/";
    static $queryCondition = array();

    public function __construct(array $config)
    {
        parent::__construct($config);
        $view = $this->input->get('view');
        if ($view) {
            $appModel = $this->getModel('applications');
            $user = JFactory::getUser();
            $this->input->set('applist',$appModel->selectAll($user->id));

            $verSion = $this->getVersion();
            $this->input->set('verSion',$verSion);
            $channels =  $this->getChannels();
            $this->input->set('channels',$channels);
        }

    }

    /**存用户设置的版本信息
     *
     */
    public function toAppSession()
    {
        $session = JFactory::getSession();
        $appModel =    $this->getModel('applications');
        $app_id= $this->input->get('app_id');
        if ($app_id) {
        	$session->set('appId', $app_id);
            $appItem = $appModel->getItem($app_id);
            if ($appItem) {
                $session->set('appRow', $appItem);
                $session->set('appName', $appItem->name);
                $session->set('appkey', $appItem->appkey);
                $session->clear('appver');
                $session->clear('appchannel');
            }
            else {
            	$session->clear('appRow');
            	$session->clear('appName');
            	$session->clear('appkey');
            }
        }


        $appver= $this->input->getString('appver');
        if ($appver) {
        	if ($appver != 'all') {
            	$session->set('appver', $appver);
        	}
        	else {
        		$session->clear('appver');
        	}
        }

        $appchannel = $this->input->getString('appchannel');
        if ($appchannel) {
        	if ($appchannel != 'all') {
            	$session->set('appchannel', $appchannel);
        	}
        	else {
        		$session->clear('appchannel');
        	}
        }

        $appstartime = $this->input->getString('appstartime');
        $appendtime = $this->input->getString('appendtime');

        if ($appstartime && $appendtime) {
             if (strtotime($appstartime) > strtotime($appendtime)) {
              $start = $appendtime;
              $appendtime = $appstartime;
              $appstartime = $start;
            }
            $session->set('appstartime', $appstartime);
            $session->set('appendtime', $appendtime);

        }

        $return_url = $_SERVER['HTTP_REFERER'];
        header("Location:$return_url");
        exit;
    }

    //获取版本号
    public function getVersion()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $session = JFactory::getSession();
        $app_id= $session->get('appId');
        if (!$app_id) {
        	$app_id = -1;
        }
        $user = JFactory::getUser();
        $r = array(
        	'username'=>$user->email,
        	'appId'=>$app_id,
        	'from'=>$from,
        	'to'=>$to
        );
        $url = $this->baseUrl.'appvers';
        $jsonData = self::getJsonData(
        	$url,
        	json_encode($r)
        );
        return json_decode($jsonData);
    }

    public function getChannels()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $session = JFactory::getSession();
        $app_id= $session->get('appId');
        if (!$app_id) {
        	$app_id = -1;
        }
        $user = JFactory::getUser();
        $r = array(
        	'username'=>$user->email,
        	'appId'=>$app_id,
        	'from'=>$from,
        	'to'=>$to
        );
        $url = $this->baseUrl.'channels';
        $jsonData = self::getJsonData(
        	$url,
        	json_encode($r)
        );
        return json_decode($jsonData);
    }

    /**api getQueryCondition
     * @param array $from
     * @param array $to
     * @param null $scale
     * @return array
     */
    protected static function getQueryCondition($from=array(), $to=array(), $extra=array())
    {
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $appchannel =  $session->get('appchannel');
        $appchannel = ($appchannel == 'All') ? '':$appchannel;
        $appver = $session->get('appver');
        $appver = ($appver == 'All') ? '':$appver;
        self::$queryCondition = array(
            "queryCondition" => array(
                "username" => $user->email,
                "where"=> array(
                    "from" => $from,
                    "to"=>$to,
                    "channels"=> $appchannel == null ? [] : [$appchannel],
                    "appkeys"=> $session->get('appkey') == null ? [] : [$session->get('appkey')],
                    "appvers"=> $appver == null ? [] : [$appver],
                    "networks"=> [],
                    "operators"=> [],
                    "models"=> [],
                    "countries"=> []
                )
            )
        );
        if ($extra && is_array($extra)) {
            self::$queryCondition = array_merge(self::$queryCondition, $extra);
        }
        return self::$queryCondition;
    }

    /**getJsonData
     * @param $url
     * @param $data
     * @return string
     */
    protected static function getJsonData($url, $data) {
		for ($i = 0; $i < 3; $i++) {
	        try {
	            $http = JHttpFactory::getHttp();
	            $resp = $http->post($url, $data, null, 30);
	            $data = $resp->body;
				break;
	        } catch (Exception $ex) {
	            $data = 'Can not fetch content: ' . $ex->getMessage();
	        }
		}
        return $data;
    }

    protected static function createYesterdayDateRange() {
    	return array(
    		'from'=> array("year"=>date("Y",strtotime("-1 day")), "month"=> date("m",strtotime("-1 day")), "day"=> date("d",strtotime("-1 day"))),
    		'to'=> array("year"=>date("Y",strtotime("-1 day")), "month"=> date("m",strtotime("-1 day")), "day"=> date("d",strtotime("-1 day")))
    	);
    }

    /**get date array
     * @param $scale
     * @return array
     */
    protected static function getDateFromTo($scale, $day = '')
    {
        switch ($scale) {
            case 'hourly':
                $array =  array(
                    'from'=> array("year"=>date("Y",strtotime("-1 day")), "month"=> date("m",strtotime("-1 day")), "day"=> date("d",strtotime("-1 day"))),
                    'to'=> array("year"=> date("Y"), "month"=> date("m"), "day"=> date("d")),
                );
                break;
            case 'day':
                if ($day == 'yesterday') {
                    $array =  array(
                        'from'=> array("year"=>date("Y",strtotime("-1 day")), "month"=> date("m",strtotime("-1 day")), "day"=> date("d",strtotime("-1 day"))),
                        'to'=> array("year"=> date("Y"), "month"=> date("m"), "day"=> date("d")),
                    );
                }else {
                    $array =  array(
                        'from'=> array("year"=>date("Y",strtotime("-7 day")), "month"=> date("m",strtotime("-7 day")), "day"=> date("d",strtotime("-7 day"))),
                        'to'=> array("year"=> date("Y"), "month"=> date("m"), "day"=> date("d")),
                    );
                }

                break;
            case 'week':
                $array =  array(
                    'from'=> array("year"=>date("Y",strtotime("-14 day")), "month"=> date("m",strtotime("-14 day")), "day"=> date("d",strtotime("-14 day"))),
                    'to'=> array("year"=> date("Y"), "month"=> date("m"), "day"=> date("d")),
                );
                break;
            case 'month':
                $array =  array(
                    'from'=> array("year"=>date("Y",strtotime("-30 day")), "month"=> date("m",strtotime("-30 day")), "day"=> date("d",strtotime("-30 day"))),
                    'to'=> array("year"=> date("Y"), "month"=> date("m"), "day"=> date("d")),
                );
                break;
        }
        $session = JFactory::getSession();
        if ( $session->get('appstartime') && $session->get('appendtime') ) {
            $array =  array(
                'from'=> array("year"=>date("Y",strtotime($session->get('appstartime'))), "month"=> date("m",strtotime($session->get('appstartime'))), "day"=> date("d",strtotime($session->get('appstartime')))),
                'to'=> array("year"=> date("Y",strtotime($session->get('appendtime'))), "month"=> date("m",strtotime($session->get('appendtime'))), "day"=> date("d",strtotime($session->get('appendtime')))),
            );
        }
        return $array;
    }


    /**NewUsers
     *
     */
    public function NewUsers() {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'newusers';

        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,array('scale'=>$scale))));
        if ($this->input->get('ajax') == 1) {
            $data = json_decode($jsonData,1);
            $list = $data['series'];
            $list['time'] = is_array($list['data']) ? array_column($list['data'], 'time') : '';
            $list['value'] = is_array($list['data']) ? array_column($list['data'], 'value') : '';
            echo(json_encode($list));exit;
        }
        $this->input->set('jsonData',$jsonData );
        $this->input->set('title','New Users' );
        $this->display();
    }

    public function yesterdayReport() {
    	$dateRange = self::createYesterdayDateRange();
    	$from = $dateRange['from'];
    	$to = $dateRange['to'];

		$dnuCount = 0;
    	$url = $this->baseUrl . 'newusers';
    	$jsonDnu = self::getJsonData($url,
    		json_encode(self::getQueryCondition($from,$to,array('scale'=>'day'))));
    	$dnu = json_decode($jsonDnu, true);
    	if (isset($dnu['series'])) {
	    	$series = $dnu['series'];
			$values = array_column($series['data'], 'value');
			if (count($values) > 0)
				$dnuCount = $values[0];
    	}

    	$dauCount = 0;
    	$url = $this->baseUrl . 'activeusers';
    	$jsonDau = self::getJsonData($url,
    		json_encode(self::getQueryCondition($from,$to,array('scale'=>'day'))));
    	$dau = json_decode($jsonDau, true);
    	if (isset($dau['series'])) {
	    	$series = $dau['series'];
			$values = array_column($series['data'], 'value');
			if (count($values) > 0)
				$dauCount = $values[0];
    	}

		echo json_encode(array(
			'dnuCount'=>$dnuCount,
			'dauCount'=>$dauCount
		));
		exit;
    }

    /**Session Duration
     *
     */
    public function SessionDuration()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'sessionduration';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,array('scale'=>$scale))));
        if ($this->input->get('ajax') == 1) {
            $data = json_decode($jsonData,1);
            $list = $data['series'];
            $list['time'] = array_column($list['data'], 'time');
            $list['value'] = array_column($list['data'], 'value');
            echo(json_encode($list));exit;
        }
        $this->input->set('jsonData',$jsonData );
        $this->input->set('title','Session Duration' );
        $this->display();
    }

    /**Session Duration
     *
     */
    public function Session()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'sessions';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        if ($this->input->get('ajax') == 1) {
            $data = json_decode($jsonData,1);
            $list = $data['series'];
            $list['time'] = array_column($list['data'], 'time');
            $list['value'] = array_column($list['data'], 'value');
            echo(json_encode($list));exit;
        }
        $this->input->set('jsonData',$jsonData );
        $this->input->set('title','Session' );
        $this->display();
    }

    /**ActiveUsers
     *
     */
    public function ActiveUsers()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'activeusers';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,array('scale'=>$scale))));

        if ($this->input->get('ajax') == 1) {
            $data = json_decode($jsonData,1);
            $list = $data['series'];
            $list['time'] = is_array($list['data'])?array_column($list['data'], 'time'):'';
            $list['value'] = is_array($list['data'])?array_column($list['data'], 'value'):'';
            echo(json_encode($list));exit;
        }
        $this->input->set('jsonData',$jsonData);
        $this->input->set('title','Active Users' );
        $this->display();
    }

    /**UsersFlow
     *
     */
    public function UsersFlow()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'userflow';

        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $this->input->set('jsonData',$jsonData );
        $this->input->set('title','Users Flow' );
        $this->display();
    }

    /**ReturningUsers
     *
     */
    public function ReturningUsers()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'returning';

        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,array('scale'=>$scale))));


        if ($this->input->get('ajax') == 1) {
            $list = json_decode($jsonData,1);
            $list['time'] = array_column($list['series']['data'], 'time');
            $list['value'] = array_column($list['series']['data'], 'value');
            echo(json_encode($list));exit;
        }


        $this->input->set('jsonData',$jsonData );
        $this->input->set('title','Returning Users' );
        $this->display();
    }

    public function Devices()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'devices';

        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        if ($this->input->get('ajax', '0') == 1) {
        	echo $jsonData;
        	exit;
        }
        $this->input->set('report',$jsonData );
        $this->display();
    }

    /**Networks
     *
     */
    public function Networks()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'networks';

        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        if ($this->input->get('ajax', '0') == 1) {
        	echo $jsonData;
        	exit;
        }
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $this->input->set('report',$jsonData );
        $this->display();
    }

    /**Language
     *
     */
    public function Language()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'languages';

        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $this->input->set('jsonData',$jsonData );
        $this->input->set('title','Language' );
        $this->display();
    }

    /**Operators
     *
     */
    public function Operators()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'operators';

        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        if ($this->input->get('ajax', '0') == 1) {
        	echo $jsonData;
        	exit;
        }        $this->input->set('report',$jsonData );
        $this->display();
    }

    /**Conversion
     *
     */
    public function Conversion()
    {
        $scale = $this->input->get('scale','day');
        $funnelId = $this->input->get('funnel_id', -1);
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'conversion';

        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,['funnelId'=>$funnelId])));

        $jsonData = str_replace('<',' lg ',$jsonData);
        $this->input->set('jsonData',$jsonData );
        $this->input->set('title','Conversion' );
        $this->display();
    }

    /**EventFrequency
     *
     */
    public function EventFrequency()
    {
        $scale = $this->input->get('scale','month');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'ecpc';

        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $items = json_decode($jsonData,true);

        $yAxis = array_column($items['data'], 'time');

        $seriesarr = [];
        if ($items['data']) {
            $seriesarr = $keys  =  [];
            foreach ($items['data'] as $key=>$val) {
                foreach ($val['series'] as $k=>$v) {
                    $seriesarr[$v['key']][$key] = $v['value'];
                }
            }


            for ($i = 0; $i < count($yAxis); $i++) {
                foreach ($seriesarr as $key => $value) {
                    foreach ($value as $vv) {
                        $seriesarr[$key][$i] = isset($seriesarr[$key][$i])? $seriesarr[$key][$i] : '';
                    }
                }
            }
            foreach ($seriesarr as $key => $value) {
                ksort($value);
                $seriesarr[$key] = $value;
            }
        }

        $this->input->set('yAxis',$yAxis);
        $this->input->set('seriesarr',$seriesarr);
        $this->input->set('title','Event Frequency' );
        $this->display();
    }

    public function getEvent()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'events';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $jsonData = str_replace('<',' lg ',$jsonData);
        return  $jsonData;
    }

    /**CountingEvent
     *
     */
    public function CountingEvent()
    {
        $scale = $this->input->get('scale','day');
        $type  = isset($_GET['type']) &&$_GET['type'] ? $_GET['type'] :'';
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'countingevents';

        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,array('name'=>$type,'scale'=>$scale))));
        $jsonData = str_replace('<',' lg ',$jsonData);
        $this->input->set('jsonData',$jsonData );
//        $this->input->set('listEvent',$this->getEvent() );
        $this->input->set('title','Counting Event' );
        $this->display();
    }

    /**CountingEvent
     *
     */
    public function ComputingEvent()
    {
        $scale = $this->input->get('scale','day');
        $type  = isset($_GET['type']) &&$_GET['type'] ? $_GET['type'] :'';
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'computingevents';

        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,array('name'=>$type,'scale'=>$scale))));
        $jsonData = str_replace('<',' lg ',$jsonData);
        $this->input->set('jsonData',$jsonData );
//        $this->input->set('listEvent',$this->getEvent() );
        $this->input->set('title','Computing Event' );
        $this->display();
    }

    /**Events
     *
     */
    public function Events()
    {
        $action = $this->input->get('action');
        $task = $this->input->get('task');
        $view= $this->input->get('view');
        $model = $this->getModel('events');
        if ($action == 'delete') {
            $id = $this->input->get('id');
            if ($model->delete($id)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task]);
            }else
                echo json_encode(['state'=>'fail','info'=>'fail']);

            die();
        }
        //store
        if ($action == 'store') {
            $inputs['app_id'] = $this->input->get('app_id');
            $inputs['event_id'] = $this->input->getString('event_id');
            $inputs['event_name'] = $this->input->getString('event_name');
            $inputs['comp_param_type'] = intval($this->input->get('comp_param_type'));
            $inputs['comp_param_name'] = $this->input->getString('comp_param_name');
            if (!$inputs['app_id']) {
                echo json_encode(['state'=>'fail','info'=>'app_id required']); die();
            }



            if ($model->store($inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task]);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        }
        //edit
        if ($action == 'update') {
            $id = $this->input->get('id');
            $inputs['app_id'] = $this->input->get('app_id');
            $inputs['event_id'] = $this->input->getString('event_id');
            $inputs['event_name'] = $this->input->getString('event_name');
            $inputs['comp_param_type'] = intval($this->input->get('comp_param_type'));
            $inputs['comp_param_name'] = $this->input->getString('comp_param_name');
            if (!$inputs['app_id']) {
                echo json_encode(['state'=>'fail','info'=>'app_id required']); die();
            }

            if ($model->update($id,$inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task]);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        }
        $this->display();
    }



    /**Applications
     *
     */
    public function Applications()
    {
        $action = $this->input->get('action');
        $task = $this->input->get('task');
        $model = $this->getModel('applications');
        //delete
        if ($action == 'delete') {
            $id = $this->input->get('id');
            if ($model->delete($id)) {
                echo json_encode(['state'=>'success']);
            }else
                echo json_encode(['state'=>'fail','info'=>'fail']);

            die();
        }
        //store
        if ($action == 'store') {
            $inputs['name'] = $this->input->getString('name');
            $inputs['package_name'] = $this->input->getString('package_name');
            if (!$inputs['name']) {
                echo json_encode(['state'=>'fail','info'=>'name required']); die();
            }
            if (!$inputs['package_name']) {
                echo json_encode(['state'=>'fail','info'=>'package_name required']); die();
            }


            if ($model->store($inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task]);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        }

        //update
        if ($action == 'update') {
            $inputs['id'] = intval($this->input->get('id'));
            $inputs['name'] = $this->input->getString('name');
            $inputs['package_name'] = $this->input->getString('package_name');
            if (!$inputs['name']) {
                echo json_encode(['state'=>'fail','info'=>'name required']); die();
            }
            if (!$inputs['package_name']) {
                echo json_encode(['state'=>'fail','info'=>'package_name required']); die();
            }

            if ($model->update($inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task]);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        }
        $this->display();
    }

    /**EventFunnel
     *
     */
    public function EventFunnel()
    {
        $action = $this->input->get('action');
        $task = $this->input->get('task');
        $model = $this->getModel('eventfunnel');
        //delete
        if ($action == 'delete') {
            $id = $this->input->get('id');
            if ($model->delete($id)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task]);
            }else
                echo json_encode(['state'=>'fail','info'=>'fail']);

            die();
        }
        //store
        if ($action == 'store') {
            $inputs['app_id'] = $this->input->get('app_id');
            $inputs['name'] = $this->input->getString('name');
            //Item
            $inputs['item'] = $this->input->get('item');

            if (!$inputs['name']) {
                echo json_encode(['state'=>'fail','info'=>'name required']); die();
            }

            if ($model->store($inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task]);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        }

        //update
        if ($action == 'update') {
            $inputs['id'] = intval($this->input->get('id'));
            $inputs['name'] = $this->input->getString('name');
            //Item
            $inputs['item'] = $this->input->get('item');

            if (!$inputs['name']) {
                echo json_encode(['state'=>'fail','info'=>'name required']); die();
            }

            if ($model->update($inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task]);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        }
        if ($action == 'ajax_event') {
            $app_id = intval($this->input->get('app_id'));
            if ($app_id > 0) {
                $events = $model->getEvents($app_id);
                echo json_encode($events);
                exit;
            }

        }
        $this->display();
    }

    /**EventFunnel
     *
     */
    public function FunnelItem()
    {
        $action = $this->input->get('action');
        $task = $this->input->get('task');
        $funnel_id = $this->input->get('funnel_id');
        $model = $this->getModel('funnelitem');
        //delete
        if ($action == 'delete') {
            $id = $this->input->get('id');
            if ($model->delete($id)) {
                echo json_encode(['state'=>'success']);
            }else
                echo json_encode(['state'=>'fail','info'=>'fail']);

            die();
        }
        //store
        if ($action == 'store') {
            $inputs['funnel_id'] = $this->input->get('funnel_id');
            $inputs['event_id'] = $this->input->getString('event_id');
            $inputs['position'] = $this->input->get('position');
            if (!$inputs['funnel_id']) {
                echo json_encode(['state'=>'fail','info'=>'funnel_id required']); die();
            }
            if (!$inputs['event_id']) {
                echo json_encode(['state'=>'fail','info'=>'event_id required']); die();
            }

            if ($model->store($inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task.'&funnel_id='.$funnel_id]);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        }

        //update
        if ($action == 'update') {
            $inputs['id'] = intval($this->input->get('id'));
            $inputs['event_id'] = $this->input->getString('event_id');
            if (!$inputs['event_id']) {
                echo json_encode(['state'=>'fail','info'=>'event_id required']); die();
            }

            if ($model->update($inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task.'&funnel_id='.$funnel_id]);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        }
        $this->display();
    }

    /*add v2.0 */


    /**getNewUserNum
     *
     */
    public function overviewAjaxSuffix()
    {
        $scale = $this->input->get('scale','day');
        $debug = $this->input->get('debug','0');
        $suffix = $this->input->getString('suffix','nutm');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.$suffix;
        if ($debug == 1) {
            $dd['url'] = $url;
            $dd['content'] = json_encode(self::getQueryCondition($from,$to));
            print_r($dd);
        }
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));;
        echo  $jsonData;
        die();
    }

    /**CampaignPerformance
     *
     */
    public function CampaignPerformance()
    {
        $scale = $this->input->get('scale','month');
        $campaign = $this->input->getString('campaign','');
        $action= $this->input->getString('action');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];

        $totals = [];
        //Total Cost
        $url = $this->baseUrl.'cptc';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to, ['campaign'=>$campaign])));
        $totalCostArray = json_decode($jsonData, true);
        $totals['cptc'] = $totalCostArray['amount'];

        //Revenue
        $url = $this->baseUrl.'cptr';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to, ['campaign'=>$campaign])));
        $totalRevenueArray = json_decode($jsonData, true);
        $totals['cptr'] = $totalRevenueArray['amount'];

        //cnames
        $url = $this->baseUrl.'cnames';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to, ['campaign'=>$campaign])));
        $cnamesArr = json_decode($jsonData, true);
        $totals['cnames'] = $cnamesArr['names'];

        $this->input->set('totals',$totals);

        $pie = $series = [];
        //pie1
        $url = $this->baseUrl.'cpnupc';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,['campaign'=>$campaign])));
        $b1arr = json_decode($jsonData, true);

        $pie['pie1']['legend'] = is_array($b1arr['data']) ? json_encode(array_column($b1arr['data'],'key')): "";
        foreach ($b1arr['data'] as $k=>$v) {
            $series[$k]['value'] = $v['value'];
            $series[$k]['name'] = $v['key'];
        }
        $pie['pie1']['series'] =  json_encode($series);

        //pie2
        $url = $this->baseUrl.'cpvupc';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,['campaign'=>$campaign])));
        $b2arr = json_decode($jsonData, true);
        $pie['pie2']['legend'] = is_array($b2arr['data']) ? json_encode(array_column($b2arr['data'],'key')): "";
        foreach ($b2arr['data'] as $k=>$v) {
            $series[$k]['value'] = $v['value'];
            $series[$k]['name'] = $v['key'];
        }
        $pie['pie2']['series'] =  json_encode($series);


        //pie3
        $url = $this->baseUrl.'cptcpc';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,['campaign'=>$campaign])));
        $b3arr = json_decode($jsonData, true);
        $pie['pie3']['legend'] = is_array($b3arr['data']) ? json_encode(array_column($b3arr['data'],'key')): "";
        foreach ($b3arr['data'] as $k=>$v) {
            $series[$k]['value'] = $v['value'];
            $series[$k]['name'] = $v['key'];
        }
        $pie['pie3']['series'] =  json_encode($series);

        //pie4
        $url = $this->baseUrl.'cpivsc';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,['campaign'=>$campaign])));
        $b4arr = json_decode($jsonData, true);
        $pie['pie4']['legend'] = is_array($b4arr['data']) ? json_encode(array_column($b4arr['data'],'key')): "";
        foreach ($b4arr['data'] as $k=>$v) {
            $series[$k]['value'] = $v['value'];
            $series[$k]['name'] = $v['key'];
        }
        $pie['pie4']['series'] =  json_encode($series);

        //cp
        $url = $this->baseUrl.'cp';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,['campaign'=>$campaign])));
        $cpArr = json_decode($jsonData, true);
        $pie['lists'] = is_array($cpArr['result']) ? $cpArr['result'] : "";

        $this->input->set('pies',$pie);

        $this->display();
    }

    /**ReTargeting
     *
     */
    public function ReTargeting()
    {
        $this->display();
    }

    /**Cohort
     *
     */
    public function Cohort()
    {
        $scale = $this->input->get('scale','day');

        $action= $this->input->getString('action');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];

        if ($action == 'ajax') {
            $campaign = $this->input->getString('campaign','');
            $city = $this->input->getString('city','');
            $group = $this->input->getString('group','');

            $url = $this->baseUrl.'cvaluation';
            $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,['campaign'=>$campaign,'groupBy'=>$group,'city'=>$city])));
            $item = json_decode($jsonData, true);
            $data['times'] = is_array($item['series'][0]['data']) ? array_column($item['series'][0]['data'],'time') : '';
            $series = [];
            foreach ($item['series'] as $key => $val) {
                $series[$key]['name'] = $val['name'];
                $series[$key]['value'] = array_column($val['data'],'value');
            }
            $data['series'] = $series;
            echo json_encode($data);
            die();
        }

        $url = $this->baseUrl.'cnames';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $cnames = json_decode($jsonData, true);
        $cohort['names'] = $cnames['names'];

        $url = $this->baseUrl.'ccities';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $ccities = json_decode($jsonData, true);
        $cohort['cities'] = $ccities['cities'];

        $this->input->set('cohort',$cohort);
        $this->display();
    }

    /**DailyRevenue
     *
     */
    public function DailyRevenue()
    {
        $scale = $this->input->get('scale','day');
        $campaign = $this->input->getString('campaign','');
        $action= $this->input->getString('action');
        $dateArray = self::getDateFromTo($scale,'yesterday');
        $from =$dateArray['from'];
        $to = $dateArray['to'];

        //drpc  堆积
        $url = $this->baseUrl.'drpc';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $items = json_decode($jsonData, true);
        $times = array_column($items['data'],'time');
        $seriesarr = $keys  =  [];
        if ($items['data']) {

            foreach ($items['data'] as $key=>$val) {
                foreach ($val['series'] as $k=>$v) {
                    $seriesarr[$v['key']][$key] = $v['value'];
                }
            }


            for ($i = 0; $i < count($times); $i++) {
                foreach ($seriesarr as $key => $value) {
                    foreach ($value as $vv) {
                        $seriesarr[$key][$i] = isset($seriesarr[$key][$i])? $seriesarr[$key][$i] : '';
                    }
                }
            }
            foreach ($seriesarr as $key => $value) {
                ksort($value);
                $seriesarr[$key] = $value;
            }
        }




        //drevenue 折线
        $url = $this->baseUrl.'drevenue';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $drevenueArray = json_decode($jsonData, true);


        $this->input->set('times',$times);
        $this->input->set('seriesarr',$seriesarr);

        $this->input->set('drevenueArray',$drevenueArray);
        $this->display();
    }

    /**TestPhones
     *
     */
    public function TestPhones()
    {
        $maxsize = 50;
        $this->input->set('maxsize',$maxsize);
        $action = $this->input->get('action');
        $task = $this->input->get('task');
        $model = $this->getModel('testphones');
        //delete
        if ($action == 'delete') {
            $id = $this->input->get('id');
            if ($model->delete($id)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task]);
            }else
                echo json_encode(['state'=>'fail','info'=>'fail']);

            die();
        }
        //store
        if ($action == 'store') {
            $count  = $model->getCount();
            if ($count > $maxsize) {
                echo json_encode(['state'=>'fail','info'=>'Beyond the maximum limit of '.$maxsize]); die();
            }
            $inputs['imei'] = $this->input->getString('imei');
            $inputs['device_id'] = $this->input->getString('device_id');
            if (!$inputs['imei'] && !$inputs['device_id']) {
                echo json_encode(['state'=>'fail','info'=>'imei or device_id  required']); die();
            }



            if ($model->store($inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task]);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        }

        //update
        if ($action == 'update') {
            $inputs['id'] = intval($this->input->get('id'));
            $inputs['imei'] = $this->input->getString('imei');
            $inputs['device_id'] = $this->input->getString('device_id');
            if (!$inputs['imei'] && !$inputs['device_id']) {
                echo json_encode(['state'=>'fail','info'=>'imei or device_id  required']); die();
            }

            if ($model->update($inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task]);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        }
        $this->display();
    }

    /**CampaignTracking
     *
     */
    public function CampaignTracking()
    {
        $action = $this->input->get('action');
        $task = $this->input->get('task');
        $appid = $this->input->get('appid');
        $model = $this->getModel('campaigntracking');

        if ($action == 'ajax' && $appid > 0) {
            $events = $model->events($appid);
            echo json_encode($events);
            exit;
        } elseif ($action == 'create') {

        } elseif ($action == 'store') {
            $inputs['app_id'] = $this->input->get('app_id');
            $inputs['name'] = $this->input->getString('name');
            $inputs['lookback_window'] = $this->input->get('lookback_window',7);
            $inputs['open_id'] = $this->input->get('open_id');


           /* $inputs['enable_sync'] = $this->input->get('enable_sync');
            if ($inputs['enable_sync']  == 1) {
                $inputs['map'] = isset($_POST['map'])?$_POST['map']:'';
            }*/

            if (!$inputs['app_id']) {
                echo json_encode(['state'=>'fail','info'=>'app_id required']); die();
            }
            if (!$inputs['name']) {
                echo json_encode(['state'=>'fail','info'=>'name required']); die();
            }

            if ($model->store($inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view='.strtolower($task).'&Itemid=127&task='.$task]);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        }


        $this->display();
    }

    public function CampaignChannel()
    {
        $action = $this->input->getString('action');
        if ($action == 'ajax') {
            $channel_id = $this->input->get('channel_id');
            $model = $this->getModel('channel');
            $channel=$model->getItem($channel_id);
            echo json_encode($channel);
            die();
        }elseif ($action == 'store') {
            $model = $this->getModel('campaignchannel');
            $inputs['campaign_id'] = $this->input->get('campaign_id');
            $inputs['channel_id'] = $this->input->get('channel_id');
            $inputs['cost_src'] = $this->input->get('cost_src');
            if ($inputs['cost_src'] == 1) {
                $inputs['cost'] = '-1';
            }
            if (!$inputs['cost_src']) {
                $inputs['cost'] = $this->input->get('cost');
            }

             $inputs['enable_sync'] = $this->input->get('enable_sync');
             if ($inputs['enable_sync']  == 1) {
                 $inputs['map'] = isset($_POST['map'])?$_POST['map']:'';
                 if (!$inputs['map']) {
                     echo json_encode(['state'=>'fail','info'=>'Sync info required']); die();
                 }
             }

            if (!$inputs['channel_id']) {
                echo json_encode(['state'=>'fail','info'=>'channel_id required']); die();
            }


            if ($model->store($inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view=campaigntracking&Itemid=127&task=CampaignTracking']);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        } elseif ($action == 'update'){
            $model = $this->getModel('campaignchannel');
            $inputs['id'] = $this->input->get('id');
            $inputs['cost_src'] = $this->input->get('cost_src');
            if ($inputs['cost_src'] == 1) {
                $inputs['cost'] = '-1';
            }
            if (!$inputs['cost_src']) {
                $inputs['cost'] = $this->input->get('cost');
            }

            $inputs['enable_sync'] = $this->input->get('enable_sync');
            if ($inputs['enable_sync']  == 1) {
                $inputs['map'] = isset($_POST['map'])?$_POST['map']:'';
                if (!$inputs['map']) {
                    echo json_encode(['state'=>'fail','info'=>'Sync info required']); die();
                }
            }


            if ($model->update($inputs)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view=campaigntracking&Itemid=127&task=CampaignTracking']);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        } elseif($action == 'delete') {
            $model = $this->getModel('campaignchannel');
            $id = $this->input->get('id');
            if ($model->delete($id)) {
                echo json_encode(['state'=>'success','url'=>'/index.php?option=com_console&view=campaigntracking&Itemid=127&task=CampaignTracking']);
            }else
                echo json_encode(['state'=>'fail','info'=>'submit fail']);

            die();
        }

        $campaign_id = $this->input->get('campaign_id');
        $channel= $this->getModel('channel');
        $this->input->set('channelist',$channel->selectAll());
        $campaign= $this->getModel('campaigntracking');
        $this->input->set('campaign',$campaign->getItem($campaign_id));
        $this->display();
    }


    /**DeepLink
     *
     */
    public function DeepLink()
    {
        $this->display();
    }

    public function Reports()
    {

    }

    public function ReportsbyWEBService()
    {

    }

    /**OverviewRevenue
     *
     */
    public function OverviewRevenue()
    {
        $scale = $this->input->get('scale','month');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'drevenue';
        $drevenueJson = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $drevenue = json_decode($drevenueJson,true);

        $time1 = is_array($drevenue['data'])?array_column($drevenue['data'],'time') : [];
        $series[0] = [
            'name' => 'Revenue',
            'value' =>  is_array($drevenue['data']) ? array_column($drevenue['data'],'value') : []
        ];


        $url = $this->baseUrl.'dcost';
        $dcostJson = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $dcost =json_decode($dcostJson,true);
        $time2 = array_column($dcost['data'],'time');
        $series[1] = [
            'name' => 'Cost',
            'value' =>  array_column($dcost['data'],'value')
        ];


        $times = array_unique(array_merge($time1,$time2));
        //时间排序
        usort($times, function($a,$b){
            $a = strtotime($a);
            $b = strtotime($b);
            if ($a == $b) {
                return 0;
            }
            return ($a < $b) ? -1 : 1;
        });
        $returnData = [
            'times' => $times,
            'series'  => $series
        ];
        echo json_encode($returnData);
        die();
    }

    public function getAudienceOverview()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'activeusers';
        $activeusersJson= self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,array('scale'=>$scale))));
        $activeusers = json_decode($activeusersJson,true);
        $times1 = array_column($activeusers['series']['data'],'time');

        $series[0] = [
            'name' => 'DAU',
            'value' =>  array_column($activeusers['series']['data'],'value')
        ];

        $url = $this->baseUrl.'sessionduration';
        $sessiondurationJson = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to,array('scale'=>$scale))));
        $sessionduration = json_decode($sessiondurationJson,true);
        $times2 = array_column($sessionduration['series']['data'],'time');
        $times = array_unique(array_merge($times1, $times2));
        usort($times, function($a,$b){
            $a = strtotime($a);
            $b = strtotime($b);
            if ($a == $b) {
                return 0;
            }
            return ($a < $b) ? -1 : 1;
        });
        $series[1] = [
            'name' => 'AVG.Session Duration',
            'value' =>  array_column($sessionduration['series']['data'],'value')
        ];

        $returnData = [
            'times' => $times,
            'series'  => $series
        ];
        return $returnData;
    }

    /**dnucOverview
     *
     */
    public function dnucOverview()
    {
        $scale = $this->input->get('scale','day');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'dnuc';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        echo $jsonData;
        die();
        $items = json_decode($jsonData,true);
//        print_r($items); exit;
        $types = $lines = [];
        $times = is_array($items['data']) ? array_column($items['data'],'time') : [];

        $seriesarr = $keys  =  [];
        if (count($times) > 0) {
            foreach ($items['data'] as $key=>$val) {
                foreach ($val['series'] as $k=>$v) {
                    $seriesarr[$v['key']][$key] = $v['value'];
                }
                $lines[] = array_sum(array_column($val['series'],'value'));
            }
            for ($i = 0; $i < count($times); $i++) {
                foreach ($seriesarr as $key => $value) {
                    foreach ($value as $vv) {
                        $seriesarr[$key][$i] = isset($seriesarr[$key][$i])? $seriesarr[$key][$i] : 0;
                    }
                }
            }
            foreach ($seriesarr as $key => $value) {
                ksort($value);
                $seriesarr[$key] = $value;
            }

        }
        $drucs['times'] = $times;
        $drucs['data'] = $seriesarr;
        $drucs['line'] = $lines;
        echo json_encode($drucs);
        die();
    }


    /**aupcOverview
     *
     */
    public function aupcOverview()
    {
        $scale = $this->input->get('scale','month');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'aupc';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $aupcs = json_decode($jsonData,true);

        $arr = [];
        if ($aupcs['data']) {
            foreach ($aupcs['data'] as $key=>$val) {
                foreach ($val['series'] as $k=>$v) {
                    $arr['data'][] = [
                        'value' => $v['value'],
                        'name'  => $v['key']
                    ];
                }
            }
        }


        echo json_encode($arr);
        exit;
    }

    /**aupcityOverview
     *
     */
    public function aupcityOverview()
    {
        $scale = $this->input->get('scale','month');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'aupcity';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $aupcs = json_decode($jsonData,true);

        $arr = [];
        if (is_array($aupcs['data']) && $aupcs['data']) {
            foreach ($aupcs['data'] as $key=>$val) {
                foreach ($val['series'] as $k=>$v) {
                    $arr['data'][] = [
                        'value' => $v['value'],
                        'name'  => $v['key']
                    ];
                }
            }
        }


        echo json_encode($arr);
        exit;
    }

    /**aupbOverview
     *
     */
    public function aupbOverview()
    {
        $scale = $this->input->get('scale','month');
        $dateArray = self::getDateFromTo($scale);
        $from =$dateArray['from'];
        $to = $dateArray['to'];
        $url = $this->baseUrl.'aupb';
        $jsonData = self::getJsonData($url,json_encode(self::getQueryCondition($from,$to)));
        $aupcs = json_decode($jsonData,true);

        $arr = [];
        if (is_array($aupcs['data']) && $aupcs['data']) {
            foreach ($aupcs['data'] as $key=>$val) {
                foreach ($val['series'] as $k=>$v) {
                    $arr['data'][] = [
                        'value' => $v['value'],
                        'name'  => $v['key']
                    ];
                }
            }
        }


        echo json_encode($arr);
        exit;
    }

	private function getJSONObject($url, $qc) {
		$json = self::getJsonData($url, $qc);
		return json_decode($json);
	}

    public function jsonOverview()
    {
		$dateArray = self::getDateFromTo('day');
		$from =$dateArray['from'];
		$to = $dateArray['to'];
		$qc = json_encode(self::getQueryCondition($from, $to,
			array('scale'=>'day')));

		$result = array(
			'nutm'=>$this->getJSONObject($this->baseUrl . 'nutm', $qc),
			'autm'=>$this->getJSONObject($this->baseUrl . 'autm', $qc),
			'rtm'=>$this->getJSONObject($this->baseUrl . 'rtm', $qc),
			'ni'=>$this->getJSONObject($this->baseUrl . 'ni', $qc),
			'nc'=>$this->getJSONObject($this->baseUrl . 'nc', $qc),
			'noi'=>$this->getJSONObject($this->baseUrl . 'noi', $qc),
			'nnoi'=>$this->getJSONObject($this->baseUrl . 'nnoi', $qc),
			'cost'=>$this->getJSONObject($this->baseUrl . 'cost', $qc),
			'dnuc'=>$this->getJSONObject($this->baseUrl . 'dnuc', $qc),
			'cost'=>$this->getJSONObject($this->baseUrl . 'cost', $qc),
			'nupc'=>$this->getJSONObject($this->baseUrl . 'nupc', $qc),
			'odrt'=>$this->getJSONObject($this->baseUrl . 'odrt', $qc),
			'nupcity'=>$this->getJSONObject($this->baseUrl . 'nupcity', $qc),
			'au'=>$this->getJSONObject($this->baseUrl . 'activeusers', $qc),
			'asd'=>$this->getJSONObject($this->baseUrl . 'sessionduration', $qc),
			'ao'=>$this->getAudienceOverview(),
			'aupc'=>$this->getJSONObject($this->baseUrl . 'aupc', $qc),
			'aupcity'=>$this->getJSONObject($this->baseUrl . 'aupcity', $qc),
			'aupb'=>$this->getJSONObject($this->baseUrl . 'aupb', $qc),
			'drevenue'=>$this->getJSONObject($this->baseUrl . 'drevenue', $qc),
			'dcost'=>$this->getJSONObject($this->baseUrl . 'dcost', $qc)
		);

		echo json_encode($result);
		die();
    }
}
